package com.penghaisoft.microwms.material.web.outwarehouse.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.RawHandOut;
import com.penghaisoft.microwms.common.data.model.RawHandOutSn;
import com.penghaisoft.microwms.common.data.model.RawRequisition;
import com.penghaisoft.microwms.common.data.model.RawRequisitionSn;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.RawBack;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawStorageSnMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.RawBackMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.RawHandOutMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.RawHandOutSnMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.RawRequisitionMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.RawRequisitionSnMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.service.IMaterialOutService;

/** 
* @ClassName: MaterialOutServiceImpl 
* @Description: TODO
* @author luoteng
* @date 2018年10月10日 上午9:47:09  
*/
@Service
public class MaterialOutServiceImpl extends BaseService implements IMaterialOutService {

    @Autowired
    private RawBackMapper rawBackMapper;
    
    @Resource
	private RawStorageSnMapper rawStorageSnMapper;
    
    @Autowired
    private RawRequisitionSnMapper rawRequisitionSnMapper;
    
    @Autowired
    private RawRequisitionMapper rawRequisitionMapper;
    
    @Autowired
    private RawHandOutMapper rawHandOutMapper;
    
    @Autowired
    private RawHandOutSnMapper rawHandOutSnMapper;
    
    /** 
     * @Description: 退料页面查询
     * @Param:  
     * @return:  
     * @Author: zhangx
     * @Date: 2018/5/21 14:25
     */ 
    @Override
    public Pager<RawBack> findRawBackListByCondition(int page, int rows, RawBack condition) {
        Pager<RawBack> pager = new Pager<>();
        pager.setPage(page);
        pager.setRows(rows);
        condition.preQuery();
        long size = rawBackMapper.queryCount(condition);
        List<RawBack> records = new ArrayList<RawBack>();
        if(size > 0){
            records = rawBackMapper.queryList(pager, condition);
            
            RawBack sumObj = rawBackMapper.querySumAmount(condition);
			
			BigDecimal oldAmount = BigDecimal.ZERO;
			BigDecimal amount = BigDecimal.ZERO;
			if (sumObj != null) {
				oldAmount = sumObj.getOldAmount() == null ? BigDecimal.ZERO : sumObj.getOldAmount();
				amount = sumObj.getAmount() == null ? BigDecimal.ZERO : sumObj.getAmount();
            }
			pager.setOrder("{\"oldAmount\":\"" + oldAmount + "\",\"amount\":\"" + amount + "\"}");
        }
        pager.setRecords(records);
        pager.setTotalCount(size);
        return pager;
    }

    @Override
    public List<RawBack> queryRawBackList(RawBack rawBack){
        return rawBackMapper.queryList(null, rawBack);
    }
    
    /* @Title: updateBack 
     * @Description: 修改最后一次 退料 pe管长度（PE管退料长度写错时使用）
     * @author luoteng
     * @date 2018年10月9日 下午4:55:16 
     */
    @Transactional
    @Override
    public TransResult updateBack(RawBack rawBack){
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	
    	BigDecimal oldAmount;
    	
    	RawStorageSn rawStorageSn = new RawStorageSn();
    	rawStorageSn.setBarcode(rawBack.getBarcode());
    	rawStorageSn.setActiveFlag("1");
    	List<RawStorageSn> list = rawStorageSnMapper.queryByAny(rawStorageSn);
    	if(list == null || list.isEmpty() || list.size() > 1){
    		result.setCode(Constant.FAIL);
    		result.setMsg("该条码库存记录存在问题！");
    		return result;
    	}else{
    		RawStorageSn tmp = list.get(0);
//    		0可用；1 冻结；2 已出库
    		if("1".equals(tmp.getBarcodeStatus())){
    			result.setCode(Constant.FAIL);
        		result.setMsg("该条码已经冻结！");
        		return result;
    		}else if("2".equals(tmp.getBarcodeStatus())){
    			result.setCode(Constant.FAIL);
        		result.setMsg("该条码已经出库！");
        		return result;
    		}
    		
    		if(rawBack.getAmount() == null){
    			result.setCode(Constant.FAIL);
    			result.setMsg("请输入长度！");
                return result;
        	}
    		
    		oldAmount = tmp.getAmount();
    		
    		String b = "[0-9]{1,}(\\.[0-9]{1,})?";
            Pattern pattern = Pattern.compile(b);
            Matcher matcher = pattern.matcher(rawBack.getAmount().toString());
            Boolean isNt = matcher.matches();
            if (!isNt){
            	result.setCode(Constant.FAIL);
            	result.setMsg("长度非数字格式！");
                return result;
            }
            
            if(rawBack.getAmount().compareTo(rawBack.getOldAmount()) > 0) {
            	result.setCode(Constant.FAIL);
            	result.setMsg("当前条码退料长度大于原长度！");
                return result;
            }
            
            tmp.setAmount(rawBack.getAmount());
        	tmp.setLastModifiedBy(rawBack.getLastModifiedBy());
        	tmp.setGmtModified(rawBack.getGmtModified());
        	
        	rawStorageSnMapper.updateBySelect(tmp);
        	
        	rawBackMapper.updateBySelect(rawBack);
        	
        	RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
            rawRequisitionSn.setBarcode(rawBack.getBarcode());
            rawRequisitionSn.setRequisitionNo(rawBack.getUserDefined1());
            rawRequisitionSn.setRequisitionType(rawBack.getUserDefined2());
            rawRequisitionSn.setModel(rawBack.getModel());
            rawRequisitionSn.setBarcode(rawBack.getBarcode());
            rawRequisitionSn.setActiveFlag("1");
            
            List<RawRequisitionSn> rawRequisitionSnList = rawRequisitionSnMapper.queryByAny(rawRequisitionSn);
            RawRequisitionSn upob = rawRequisitionSnList.get(0);
            upob.setBackAmount(rawBack.getAmount());
        	
            rawRequisitionSnMapper.updateBySelect(upob);
            
            RawRequisition rawRequisition = new RawRequisition();
            rawRequisition.setRequisitionId(upob.getRequisitionId());
            rawRequisition.setBackAmountAdd(rawBack.getAmount().subtract(oldAmount));
            rawRequisitionMapper.updateBySelect(rawRequisition);
    	}
    	
    	return result;
    }
    

    /* @Title: updateBack 
     * @Description: 修改最后一次 退料 pe管长度（PE管退料长度写错时使用）【手工出库】
     * @author luoteng
     * @date 2018年10月9日 下午4:55:16 
     */
    @Transactional
    @Override
    public TransResult updateSGBack(RawBack rawBack){
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	
    	BigDecimal oldAmount;
    	
    	RawStorageSn rawStorageSn = new RawStorageSn();
    	rawStorageSn.setBarcode(rawBack.getBarcode());
    	rawStorageSn.setActiveFlag("1");
    	List<RawStorageSn> list = rawStorageSnMapper.queryByAny(rawStorageSn);
    	if(list == null || list.isEmpty() || list.size() > 1){
    		result.setCode(Constant.FAIL);
    		result.setMsg("该条码库存记录存在问题！");
    		return result;
    	}else{
    		RawStorageSn tmp = list.get(0);
//    		0可用；1 冻结；2 已出库
    		if("1".equals(tmp.getBarcodeStatus())){
    			result.setCode(Constant.FAIL);
        		result.setMsg("该条码已经冻结！");
        		return result;
    		}else if("2".equals(tmp.getBarcodeStatus())){
    			result.setCode(Constant.FAIL);
        		result.setMsg("该条码已经出库！");
        		return result;
    		}
    		
    		if(rawBack.getAmount() == null){
    			result.setCode(Constant.FAIL);
    			result.setMsg("请输入长度！");
                return result;
        	}
    		
    		oldAmount = tmp.getAmount();
    		
    		String b = "[0-9]{1,}(\\.[0-9]{1,})?";
            Pattern pattern = Pattern.compile(b);
            Matcher matcher = pattern.matcher(rawBack.getAmount().toString());
            Boolean isNt = matcher.matches();
            if (!isNt){
            	result.setCode(Constant.FAIL);
            	result.setMsg("长度非数字格式！");
                return result;
            }
            
            if(rawBack.getAmount().compareTo(rawBack.getOldAmount()) > 0) {
            	result.setCode(Constant.FAIL);
            	result.setMsg("当前条码退料长度大于原长度！");
                return result;
            }
            
            tmp.setAmount(rawBack.getAmount());
        	tmp.setLastModifiedBy(rawBack.getLastModifiedBy());
        	tmp.setGmtModified(rawBack.getGmtModified());
        	
        	rawStorageSnMapper.updateBySelect(tmp);
        	
        	rawBackMapper.updateBySelect(rawBack);
        	
        	RawHandOutSn rawHandOutSnentity = new RawHandOutSn();
    		rawHandOutSnentity.setBarcode(rawBack.getBarcode());
    		List<RawHandOutSn> rawHandOutSnLis = rawHandOutSnMapper.queryHandOutSnByDesc(rawHandOutSnentity);
    		
    		RawHandOutSn handSn = rawHandOutSnLis.get(0);
    		
    		handSn.setBackAmount(rawBack.getAmount());
            handSn.setLastModifiedBy(rawBack.getLastModifiedBy());
            handSn.setGmtModified(rawBack.getGmtModified());
            rawHandOutSnMapper.updateBySelect(handSn);
            
            RawHandOut rawHandOut = new RawHandOut();
            rawHandOut.setHandOutId(handSn.getHandOutId());
            rawHandOut.setBackAmount(rawBack.getAmount());
            rawHandOut.setLastModifiedBy(rawBack.getLastModifiedBy());
            rawHandOut.setGmtModified(rawBack.getGmtModified());
            rawHandOutMapper.updateBySelect(rawHandOut);
    	}
    	
    	return result;
    }
    
    /* @Title: updateBack 
     * @Description: 修改最后一次 退料 pe管长度（PE管退料长度写错时使用）（校验）
     * @author luoteng
     * @date 2018年10月9日 下午4:55:16 
     */
    @Override
    public TransResult updateBackCheck(RawBack rawBack){
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	
    	BigDecimal oldAmount;
    	
    	RawStorageSn rawStorageSn = new RawStorageSn();
    	rawStorageSn.setBarcode(rawBack.getBarcode());
    	rawStorageSn.setActiveFlag("1");
    	List<RawStorageSn> list = rawStorageSnMapper.queryByAny(rawStorageSn);
    	if(list == null || list.isEmpty() || list.size() > 1){
    		result.setCode(Constant.FAIL);
    		result.setMsg("该条码库存记录存在问题！");
    		return result;
    	}else{
    		RawStorageSn tmp = list.get(0);
//    		0可用；1 冻结；2 已出库
    		if("1".equals(tmp.getBarcodeStatus())){
    			result.setCode(Constant.FAIL);
        		result.setMsg("该条码已经冻结！");
        		return result;
    		}else if("2".equals(tmp.getBarcodeStatus())){
    			result.setCode(Constant.FAIL);
        		result.setMsg("该条码已经出库！");
        		return result;
    		}
    		
    		if(rawBack.getAmount() == null){
    			result.setCode(Constant.FAIL);
    			result.setMsg("请输入长度！");
                return result;
        	}
    		
    		oldAmount = tmp.getAmount();
    		
    		String b = "[0-9]{1,}(\\.[0-9]{1,})?";
            Pattern pattern = Pattern.compile(b);
            Matcher matcher = pattern.matcher(rawBack.getAmount().toString());
            Boolean isNt = matcher.matches();
            if (!isNt){
            	result.setCode(Constant.FAIL);
            	result.setMsg("长度非数字格式！");
                return result;
            }
            
            if(rawBack.getAmount().compareTo(rawBack.getOldAmount()) > 0) {
            	result.setCode(Constant.FAIL);
            	result.setMsg("当前条码退料长度大于原长度！");
                return result;
            }
    	}
    	
    	return result;
    }
    
    /* @Title: queryRawStorageSnList 
     * @Description: 查询原材料库存明细
     * @author luoteng
     * @date 2018年10月10日 上午9:47:17 
     */
    @Override
    public List<RawStorageSn> queryRawStorageSnList(RawStorageSn rawStorageSn){
    	return rawStorageSnMapper.queryByAny(rawStorageSn);
    }
}
